package com.example.springboot.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.common.Constants;
import com.example.springboot.controller.dto.UserDto;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import org.springframework.stereotype.Service;

/**
 * @Author: ShanYuqing
 * @Version: v1.0
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    public User insert(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        if(user.getId()!=null){
        queryWrapper.ne("id",user.getId());
        }
        User one = getOne(queryWrapper);
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(user, one, true);
            saveOrUpdate(one);
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }
//        if(user.getId() == null){  //user没有id则表示新增
//          return save(user);
//       }else { //否则为更新
//          return  updateById(user);
//
//    @Autowired
//    private UserMapper userMapper;
//    public int insert(User user){
//        if(user.getId() == null){  //user没有id则表示新增
//         return userMapper.insert(user);
//        }else { //否则为更新
//         return userMapper.update(user);
//
//        }

    public UserDto login(UserDto userdto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userdto.getUsername());
        queryWrapper.eq("password", userdto.getPassword());
        User one = getOne(queryWrapper);
        if (one != null) {
            BeanUtil.copyProperties(one, userdto, true);
            return userdto;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }

    }

    public User register(UserDto userdto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userdto.getUsername());
        User one = getOne(queryWrapper);
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(userdto, one, true);
            save(one);
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }
}
